const LibraryModel = require('../models/library-model')
// 根据媒体信息猜测媒体库
const guessLibrary = async ({mediaType, genre_ids, original_language, origin_country }) => {
    let libraryMathedId;
    //1.查找已配置分类的媒体库
    const librarys = await LibraryModel.list(LibraryModel.buildPaging({ sortField: 'order', sortOrder: 'ascend' }), modelQuery => {
        modelQuery.where('media_type', mediaType)
    })
    if (librarys && librarys.length) {
        // 2.根据链接规则选择合适的媒体库
        // {"genre_ids":"","original_language":"","origin_country":""}
        let librarysWithRules = [];   // 有规则的媒体库
        let librarysWithoutRules = []; // 无规则的媒体库
        for (let index = 0; index < librarys.length; index++) {
            const library = librarys[index];
            if (library.rules) {
                const linkRules = JSON.parse(library.rules)
                if (linkRules.genre_ids || linkRules.original_language || linkRules.origin_country) {
                    librarysWithRules.push(library)
                } else {
                    librarysWithoutRules.push(library)
                }
            } else {
                librarysWithoutRules.push(library)
            }
        }

        if (librarysWithRules.length) {
            // 3.有规则的媒体库，根据规则匹配
            for (let index = 0; index < librarysWithRules.length; index++) {
                const library = librarysWithRules[index];

                if (!library.folder) continue; // 媒体库没有设置目录，跳过

                const linkRules = JSON.parse(library.rules)

                // 1).匹配内容类型
                // TODO 获取 TMDB info
                const media_genre_ids = genre_ids; // [1, 2, 3];
                const genre_ids_match = !linkRules.genre_ids || media_genre_ids.some((genre_id) => {
                    return linkRules.genre_ids.split(',').includes(genre_id.toString())
                })
                // 2).匹配语种
                // TODO 获取 TMDB info
                const media_original_language = original_language; // 'en';
                const original_language_match = !linkRules.original_language || linkRules.original_language.split(',').includes(media_original_language)
                // 3).匹配国家/地区
                // TODO 获取 TMDB info
                const media_origin_countrys =  origin_country; // ['US'];
                const origin_country_match = !linkRules.origin_country || media_origin_countrys.some((media_origin_country) => {
                    return linkRules.origin_country.split(',').includes(media_origin_country)
                })

                if (genre_ids_match && original_language_match && origin_country_match) {
                    libraryMathedId = library.id;
                    break;
                }
            }

        }

        // 4.还未匹配到媒体库，使用第一个无规则媒体库
        if (!libraryMathedId && librarysWithoutRules.length) {
            libraryMathedId = librarysWithoutRules[0].id
        }
    }

    return libraryMathedId;
}

module.exports = {
    guessLibrary
}